import { ConverterBase } from './base';
import { EditBox, Label, Sprite, UITransform } from './cc';
import { enum_ } from '../../model';

export class EditBoxConverter extends ConverterBase {
    public static prefix = 'eb-';

    public async convert() {
        let mainNode, spriteFrame, labelNode;
        const children = this.treePSD.children()
        for (let i = 0; i < children.length; i++) {
            const name = children[i].get<string>(enum_.Psd.name);
            if (name.startsWith('simg')) {
                mainNode = await this.factory.build(children[i]).convert();
                mainNode.position = this.createVec3(this.x, this.y);
                spriteFrame = mainNode.getComponent(ConverterBase.getCcPropFunc(Sprite.name)).spriteFrame;
            } else if (name.includes('.Sprite')) {
                mainNode = this.createNode();
                const sprite = await this.appendSprite(children[i], mainNode);
                spriteFrame = sprite.spriteFrame;
            } else {
                labelNode = await this.factory.build(children[i]).convert();
            }
        }
        mainNode ??= this.createNode();

        const label = labelNode?.getComponent(ConverterBase.getCcPropFunc(Label.name));
        if (labelNode) {
            label.overflow = 2;
            const labelTransform = labelNode.getComponent(ConverterBase.getCcPropFunc(UITransform.name));
            const mainTransform = mainNode.getComponent(ConverterBase.getCcPropFunc(UITransform.name));
            labelTransform.width = mainTransform.width;
            labelTransform.height = mainTransform.height;
            labelNode.parent = mainNode;
        }

        const editBox = this.appendComponent(EditBox, mainNode);
        if (editBox) {
            editBox.backgroundImage = spriteFrame || null;
            editBox.placeholderLabel = label || '';
        }

        return mainNode;
    }
}